import json
import requests
from common.yaml_util import *


class RequestsUtil:

    session = requests.session()

    def __init__(self,home,base_url):
        self.base_url = read_config_file(home,base_url)
        self.last_headers = {}

    def replace_value(self, data):
        # 判断数据类型
        if data and isinstance(data, dict):  # data 不为空且data是个字典
            str = json.dumps(data)
        else:
            str = data

        # 替换数据
        for a in range(1, str.count('{{') + 1):
            if '{{' in str and '}}' in str :
                start_index = str.index('{{')
                end_index = str.index('}}')
                old = str[start_index:end_index + 2]
                new = read_extract_file(old[2:-2])
                str = str.replace(old,new)
                # print(str)

        # 还原数据类型
        if data and isinstance(data, dict):
            data = json.loads(str)
        else:
            data = str
        return data

    def send_request(self,method,url,headers=None,**kwargs):
        #处理method
        self.last_method = str(method).lower()

        #处理基础路径
        self.base_url =self.base_url + self.replace_value(url)

        #处理请求头
        if headers and isinstance(headers,dict):
            self.last_headers = self.replace_value(headers)
        #请求数据替换
        for key,value in kwargs.items():
            if key in ['params','data','json']:
                kwargs[key] = self.replace_value(value)



        res = RequestsUtil.session.request(method=self.last_method,url=self.base_url,headers=self.last_headers,**kwargs)
        return res
#
#
# #wip 加入获取项目基础路径以达到应付不同环境运行
# class RequestsUtilCompny:
#
#     session = requests.session()
#
#     def __init__(self,company,base_url):        #环境改这里
#         self.base_url = read_config_file(company,base_url)
#
#     def send_request(self,method,url,**kwargs):
#         self.last_method = str(method).lower()
#         self.base_url = self.base_url + url
#         res = RequestsUtil.session.request(method=self.last_method,url=self.base_url,**kwargs)
#         return res
#
# class RequestsUtilSchool:
#
#     session = requests.session()
#
#     def __init__(self,school,base_url):        #环境改这里
#         self.base_url = read_config_file(school,base_url)
#
#     def send_request(self,method,url,**kwargs):
#         self.last_method = str(method).lower()
#         self.base_url = self.base_url + url
#         res = RequestsUtil.session.request(method=self.last_method,url=self.base_url,**kwargs)
#         return res


# #统一替换值方法,data可以是url（string）也可以是参数（字典）或者请求头
# def replace_value(self,data):
#     #判断数据类型
#     if data and isinstance(data,dict):# data 不为空且data是个字典
#         str = json.dumps(data)
#     else:
#         str = data
#
#     #替换数据
#     for a in range(1,data.count('{{')+1):
#         if '{{' and '}}' in datd :
#             start_index = data.index('{{')
#             end_index = data.index('}}')
#             old = data[start_index:end_index+2]
#             new = read_extract_file(old[2:-2])
#             str = data.replace(old,new)
#             #print(data)
#
#     #还原数据类型
#     if data and isinstance(data,dict):
#         data = json.loads(str)
#     else:
#         data = str
#
#
# if __name__ == '__main__':
#     url = 'daldasldalsdas{{token}}'
#     for a in range(1,url.count('{{')+1):
#         if '{{' and '}}' in url :
#             start_index = url.index('{{')
#             end_index = url.index('}}')
#             old = url[start_index:end_index+2]
#             new = read_extract_file(old[2:-2])
#             url = url.replace(old,new)
#             print(url)